export default {
    // 添加命名空间
    namespaced:'car',
    state:{
        carList:[]
    },
    getters:{
        totalPrice(state){
            return state.carList.reduce((pre,cur)=>pre + cur.price * cur.buyNum,0)
        }
    },
    actions:{
        addCar({state,commit}, goods){ // {gname:'', price:2000}
            console.log('addCar',goods)
            // 判断商品在不在购物车中 ? find   findIndex
            let index = state.carList.findIndex(item=>item.id === goods.id)
            if(index === -1){ // 当前商品不在购物车中，新增
                commit('ADD_CAR', {
                    ...goods,
                    buyNum:1
                })
            }else{// 在购物车中，累计buyNum数量
                commit('CHANGE_BUYNUM', {index,buyNum:1})
            }
        },
        changeNum({state,commit},{ id, buyNum}){
            let index = state.carList.findIndex(item=>item.id === id)
            let nowBuyNum = state.carList[index].buyNum
            nowBuyNum += buyNum
            if(nowBuyNum <=0 ){ // 将该商品移除购物车列表
                commit('REMOVE_CAR', index)
            }else{
                commit('CHANGE_BUYNUM', {index, buyNum})
            }
        }
    },
    mutations:{
        ADD_CAR(state, goods){
            state.carList.push(goods)
        },
        CHANGE_BUYNUM(state, {index, buyNum}){
            state.carList[index].buyNum += buyNum
        },
        REMOVE_CAR(state, index){
            state.carList.splice(index, 1)
        }
    }
}